<?php
/**
 * API控制器
 */

declare (strict_types = 1);

namespace app\controller\home;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Api extends BaseController
{
    /**
     * 首页公告列表
     */
    public function get_note_list()
    {
        try {
            $list = Db::name('note')
                ->field('a.id,a.title,a.create_time,c.title as cate_title')
                ->alias('a')
                ->join('note_cate c', 'a.cate_id = c.id')
                ->where(['a.status' => 1, 'a.delete_time' => 0])
                ->order('a.end_time desc,a.sort desc,a.create_time desc')
                ->limit(8)
                ->select()
                ->each(function($item) {
                    $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                    return $item;
                });
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 首页知识列表
     */
    public function get_article_list()
    {
        try {
            // 检查是否安装了文章模块
            $prefix = config('database.connections.mysql.prefix');
            $exist = Db::query("SHOW TABLES LIKE '{$prefix}article'");
            
            $list = [];
            if ($exist) {
                $list = Db::name('article')
                    ->field('a.id,a.title,a.create_time,a.read,c.title as cate_title')
                    ->alias('a')
                    ->join('article_cate c', 'a.cate_id = c.id')
                    ->where(['a.delete_time' => 0])
                    ->order('a.id desc')
                    ->limit(8)
                    ->select()
                    ->each(function($item) {
                        $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                        return $item;
                    });
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取访问记录
     */
    public function get_view_data()
    {
        try {
            $firstTime = time();
            $secondTime = $firstTime - 86400;
            $threeTime = $firstTime - 86400 * 365;
            $beginFirst = strtotime(date('Y-m-d', $firstTime) . " 00:00:00");
            $endFirst = strtotime(date('Y-m-d', $firstTime) . " 23:59:59");
            $beginSecond = strtotime(date('Y-m-d', $secondTime) . " 00:00:00");
            $endSecond = strtotime(date('Y-m-d', $secondTime) . " 23:59:59");
            $beginThree = strtotime(date('Y-m-d', $threeTime) . " 00:00:00");
            
            $dataFirst = Db::name('admin_log')
                ->field('create_time')
                ->whereBetween('create_time', [$beginFirst, $endFirst])
                ->select()
                ->toArray();
            
            $dataSecond = Db::name('admin_log')
                ->field('create_time')
                ->whereBetween('create_time', [$beginSecond, $endSecond])
                ->select()
                ->toArray();
            
            $dataThree = Db::name('admin_log')
                ->field('create_time')
                ->whereBetween('create_time', [$beginThree, $endFirst])
                ->select()
                ->toArray();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'data_first' => $this->hourDocument($dataFirst),
                    'data_second' => $this->hourDocument($dataSecond),
                    'data_three' => $dataThree
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 按小时统计文档
     */
    private function hourDocument($data)
    {
        $hours = array_fill(0, 24, 0);
        foreach ($data as $item) {
            $hour = date('H', $item['create_time']);
            $hours[(int)$hour]++;
        }
        return $hours;
    }
    
    /**
     * 获取员工活跃数据
     */
    public function get_view_log()
    {
        try {
            $times = strtotime("-30 day");
            $where = [];
            $where[] = ['uid', '<>', 1];
            $where[] = ['create_time', '>', $times];
            
            $list = Db::name('admin_log')
                ->field("id,uid")
                ->where($where)
                ->select()
                ->toArray();
            
            $logs = [];
            foreach ($list as $value) {
                $uid = $value['uid'];
                if (empty($logs[$uid])) {
                    $logs[$uid]['count'] = 1;
                    $logs[$uid]['name'] = Db::name('admin')->where('id', $uid)->value('name');
                } else {
                    $logs[$uid]['count'] += 1;
                }
            }
            
            // 按count排序
            $counts = array_column($logs, 'count');
            array_multisort($counts, SORT_DESC, $logs);
            
            // 截取前10
            $dataLogs = array_slice($logs, 0, 10);
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'data_logs' => $dataLogs
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取地区数据
     */
    public function areaJson()
    {
        try {
            $param = Request::param();
            $type = isset($param['type']) ? $param['type'] : 'province';
            
            if ($type == 'province') {
                $data = Db::name('area')
                    ->where(['level' => 1, 'status' => 1])
                    ->column('name', 'id');
            } elseif ($type == 'city') {
                $data = Db::name('area')
                    ->where(['level' => 2, 'status' => 1])
                    ->column('name', 'id');
            } elseif ($type == 'district') {
                $data = Db::name('area')
                    ->where(['level' => 3, 'status' => 1])
                    ->column('name', 'id');
            } else {
                $data = [];
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取省份
     */
    public function regionProvinces()
    {
        try {
            $provinceList = Db::name('region')
                ->where('level', 1)
                ->order('pinyin', 'ASC')
                ->select();
            
            return json([
                'status' => 'SUCCESS',
                'data' => $provinceList
            ]);
        } catch (\Exception $e) {
            return json(['status' => 'ERROR', 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取城市
     */
    public function regionCitys()
    {
        try {
            $param = Request::param();
            $provinceId = isset($param['provinceId']) ? $param['provinceId'] : 0;
            
            $cityList = Db::name('region')
                ->where('level', 2)
                ->where('parent_id', $provinceId)
                ->order('pinyin', 'ASC')
                ->select();
            
            return json([
                'status' => 'SUCCESS',
                'data' => $cityList
            ]);
        } catch (\Exception $e) {
            return json(['status' => 'ERROR', 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取区域
     */
    public function regionDists()
    {
        try {
            $param = Request::param();
            $cityId = isset($param['cityId']) ? $param['cityId'] : 0;
            
            $distList = Db::name('region')
                ->where('level', 3)
                ->where('parent_id', $cityId)
                ->order('pinyin', 'ASC')
                ->select();
            
            return json([
                'status' => 'SUCCESS',
                'data' => $distList
            ]);
        } catch (\Exception $e) {
            return json(['status' => 'ERROR', 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
}